<?php
	class attachment extends spModel
	{
		var $error;

		function upload($name)
		{
			$savepath = UPLOAD_PATH . '/' . date('Y/md/');
			if(!$this->dir_create($savepath)) {
				$this->error = '8';
				return false;
			}
			if(!is_dir($savepath)) {
				$this->error = '8';
				return false;
			}
			@chmod($savepath, 0777);
			if(!is_writeable($savepath)) {
				$this->error = '9';
				return false;
			}
			$uploadfile = array('tmp_name' => $_FILES[$name]['tmp_name'], 'name' => $_FILES[$name]['name'], 'type' => $_FILES[$name]['type'], 'size' => $_FILES[$name]['size'], 'error' => $_FILES[$name]['error'], 'description'=>$description,'fn'=>$fn);
			$fileext = $this->fileext($uploadfile['name']);
			$temp_filename = $this->getname($fileext);
			$savefile = $savepath.$temp_filename;
			if(!$this->isuploadedfile($uploadfile['tmp_name'])) {
				$this->error = '12';
				return false;
			}
			$savefile = preg_replace("/(php|phtml|php3|php4|jsp|exe|dll|asp|cer|asa|shtml|shtm|aspx|asax|cgi|fcgi|pl)(\.|$)/i", "_\\1\\2", $savefile);

			move_uploaded_file($uploadfile['tmp_name'], $savefile);
			return '/' . date('Y/md/') . $temp_filename;
		}
		
		/**
		 * 获取附件名称
		 * @param $fileext 附件扩展名
		 */
		function getname($fileext)
		{
			return date('Ymdhis').rand(100, 999).'.'.$fileext;
		}

		/**
		 * 取得文件扩展
		 * 
		 * @param $filename 文件名
		 * @return 扩展名
		 */
		function fileext($filename) {
			return strtolower(trim(substr(strrchr($filename, '.'), 1, 10)));
		}

		/**
		* 转化 \ 为 /
		* 
		* @param	string	$path	路径
		* @return	string	路径
		*/
		function dir_path($path) {
			
			$path = str_replace('\\', '/', $path);
			if(substr($path, -1) != '/') $path = $path.'/';
			return $path;
		}
		/**
		* 创建目录
		* 
		* @param	string	$path	路径
		* @param	string	$mode	属性
		* @return	string	如果已经存在则返回true，否则为flase
		*/
		function dir_create($path, $mode = 0777) {
			
			if(is_dir($path)) return TRUE;
			$ftp_enable = 0;
			$path = $this->dir_path($path);

			$temp = explode('/', $path);
			$cur_dir = '';
			
			$max = count($temp) - 1;
			for($i=0; $i<$max; $i++) {
				$cur_dir .= $temp[$i].'/';
				if (@is_dir($cur_dir)) continue;
				@mkdir($cur_dir, 0777,true);
				@chmod($cur_dir, 0777);
			}
			return is_dir($path);
		}

		/**
		* 判断文件是否是通过 HTTP POST 上传的
		*
		* @param	string	$file	文件地址
		* @return	bool	所给出的文件是通过 HTTP POST 上传的则返回 TRUE
		*/
		function isuploadedfile($file) {
			return is_uploaded_file($file) || is_uploaded_file(str_replace('\\\\', '\\', $file));
		}
	}
?>